package com.wosaitech.baby.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wosaitech.baby.dao.DataDao;
import com.wosaitech.baby.entry.Score;
import com.wosaitech.baby.entry.User;
import com.wosaitech.baby.entry.WXUser;
import com.wosaitech.baby.pojo.ScoreResult;
import com.wosaitech.baby.restful.JsonResult;
import com.wosaitech.baby.utils.DateUtils;

@Controller
public class ServiceController extends BaseController {

	@Autowired
	private DataDao dataDao;

	@Autowired
	private HttpServletRequest request;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String defaultMethod() {
		System.out.println("defaultMethod");
		return "myindex";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@ModelAttribute("user") User user) throws Exception {
		System.out.println("login");
		return "myindex";
	}

	@RequestMapping(method = RequestMethod.GET, value = "/queryScore/{openId}")
	public void queryScore(@PathVariable String openId,
			HttpServletResponse response, @RequestHeader HttpHeaders headers)
			throws IOException {
		int point = dataDao.queryScoreByOpenId(openId);
		JsonResult result = new JsonResult();
		result.setCurRec(1);
		result.setResult(0);
		result.setPoint(point);
		result.setMessage("查询成功");
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(JSON.toJSON(result).toString());
		out.close();
	}

	@RequestMapping(method = RequestMethod.GET, value = "/saveUser/{openId}/{userinfo}")
	public void saveUser(@PathVariable String openId,
			@PathVariable String userinfo, HttpServletResponse response,
			@RequestHeader HttpHeaders headers) throws IOException {
		System.out.println("userinfo:" + userinfo);
		JSONObject obj = (JSONObject) JSON.parse(userinfo);
		String phone = (String) obj.get("phone");
		String address = (String) obj.get("address");
		WXUser wxu = dataDao.getWXUserByOpenId(openId);
		if (wxu == null) {
			wxu = new WXUser();
			wxu.setWeixin_openid(openId);
		}
		wxu.setPhone(phone);
		wxu.setUpdateTime(new Date());
		wxu.setAddress(address);
		dataDao.save(wxu);
		JsonResult result = new JsonResult();
		result.setCurRec(1);
		result.setResult(0);
		result.setMessage("提交成功");
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(JSON.toJSON(result).toString());
		out.close();
	}

	@RequestMapping(method = RequestMethod.GET, value = "/saveScore/{openId}/{shareOpenId}/{point}/{userjson}")
	public void saveScore(@PathVariable String openId,
			@PathVariable String shareOpenId, @PathVariable String point,
			@PathVariable String userjson, HttpServletResponse response,
			@RequestHeader HttpHeaders headers) throws IOException {
		WXUser wxu = dataDao.getWXUserByOpenId(openId);
		if (wxu == null) {
			wxu = new WXUser();
			wxu.setWeixin_openid(openId);
			wxu.setCreateTime(new Date());
		}
		wxu.setWeixin_userjson(userjson);
		dataDao.save(wxu);

		boolean has = dataDao.hasScoreByOpenIdAndShareOpenId(shareOpenId,
				openId);
		if (!has) {
			// 替别人玩
			Score score = new Score();
			score.setOpenId(shareOpenId);
			score.setShareOpenId(openId);
			score.setCreatedate(new Date());
			score.setPoint(300);
			dataDao.save(score);
		} else {
			int count = dataDao.queryCountScore(openId);
			if (count < 3) {
				// 给自己玩
				Score score = new Score();
				score.setOpenId(openId);
				score.setPoint(300);
				score.setCreatedate(new Date());
				dataDao.save(score);
			}
		}
		JsonResult result = new JsonResult();
		result.setCurRec(1);
		result.setResult(0);
		result.setMessage("提交成功");
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print(JSON.toJSON(result).toString());
		out.close();
	}

	@RequestMapping(value = "/rank", method = RequestMethod.GET)
	public String rank() {
		return "rank";
	}

	@RequestMapping(value = "/rankList", method = RequestMethod.POST)
	public String rankList(@RequestParam("year") Integer year,
			@RequestParam("month") Integer month,
			@RequestParam("point") Integer point) {
		System.out.println(year + "|" + month + "|" + point);
		int ps1 = 0, ps2 = 0;
		if (point == 3000) {
			ps1 = 3000;
			ps2 = 6000;
		} else if (point == 6000) {
			ps1 = 6000;
			ps2 = 10000;
		} else if (point == 10000) {
			ps1 = 10000;
		}
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		List<ScoreResult> srList = dataDao.findScoreResultByDateAndScore(
				DateUtils.getMonthStart(cal), DateUtils.getMonthEnd(cal), ps1,
				ps2);
		request.setAttribute("srList", srList);
		return "rankList";
	}

	@InitBinder("user")
	public void initBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("user.");
	}
}